//引入express 模块
var express = require('express');
//创建APP
var app = express();
//创建server
var server = require('http').createServer(app);
//引入body-parser用来接收post请求
var bodyParser = require('body-parser');
//引入MD5加密模块
var md5 = require('./md5');
const rimraf = require('rimraf');
//引入用户数据源
var users = require('./datasource/user');
//引入角色数据源
var roles = require('./datasource/role');
//引入员工数据源
var empls = require('./datasource/employee');
//引入path
var path = require('path');
//引入multer模块
var multer = require('multer');
//引入文件模块fs
var fs = require('fs');
//photo就是页面传过来的那个文件的name，1代表最多能传1个。
app.use(multer({ dest: 'tmp' }).array('photo', 1));
//解析post数据
app.use(express.urlencoded({ extended: true }));
//托管静态文件
app.use(express.static(__dirname + '/src'));
//网站入口
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/src/pages/index.html');
});

// 登录页的入口
// app.get('/login.html',(req,res)=>{
//     res.sendFile(__dirname+'/src/pages/login.html');
// });

//登录
app.post('/login.do', (req, res) => {
    var username = req.body.username;
    var password = md5(req.body.password);

    if (!username || !password) {
        res.send('fail');
        return;
    }
    for (u of users) {
        if (u.username === username && u.password === password) {

            res.send('success');
            return;
        }
    } res.send('fail');
});
//查询用户列表
app.get('/user.do', (req, res) => {
    res.send(users);
});
//查询角色列表
app.get('/Role.do', (req, res) => {
    res.send(roles);
});
//查询员工列表
app.get('/employee.do', (req, res) => {
    for (var i = 0; i < empls.length; i++) {
        if (empls[i].state == 0) {
            empls.splice(i, 1);
        }
    }
    res.send(empls);
});

//重置用户密码
app.post('/resetPass.do', (req, res) => {
    let id = req.body.id;
    let new_pass = req.body.password;
    for (u of users) {
        if (u.id == id) {
            u.password = md5(new_pass);
            res.send('success');
            return;
        }
    }
    res.send('fail');
})

//修改用户状态(0：冻结，1正常)
app.post('/change_state.do', (req, res) => {
    let id = req.body.id;
    let state = req.body.state;
    for (u of users) {
        if (u.id == id) {
            u.state = state;
            res.send('success');
            return;
        }
    }
    res.send('fail');
});

//添加用户
app.post('/addUser.do', (req, res) => {
    let username = req.body.username;
    let password = md5(req.body.password);
    let phone = req.body.phone;
    let id = users[users.length - 1].id + 1;
    let state = 1;
    if (username && password && phone) {
        users.push({
            username, password, phone, id, state
        });
        res.send('success');
    } else {
        res.send('fail');
    }
});
//添加角色
app.post('/addRole.do', (req, res) => {
    let role = req.body.role;
    //判断用户是否已添加
    for (rol of roles) {
        if (rol == role) {
            res.send('no');
            return;
        }
    }
    if (role) {
        roles.push(role);
        res.send('success');
    }
    else {
        res.send('fail');
    }
});
//添加员工
app.post('/alterEmpls.do', (req, res) => {
    let file = req.files[0];
    let name = req.body.name;
    let id = empls[empls.length - 1].id + 1; 
    //创建10位随机字符串  
    var str = 'abcdefghijklmnpqrstuvwxy1234567891';
    var imgstr = '';
    for(var i=0;i<10;i++){
     var mat = Math.floor(Math.random()*36)
        imgstr += str.substring(mat,mat+1);
    }
    let imgName = id+name+imgstr+'.'+file.originalname.split('.')[1];
    //获取原始文件的名字
    // var url = __dirname + '/src/assets/img/' + file.originalname;
    var url = __dirname + '/src/assets/img/' + imgName;
    var data = fs.readFileSync(file.path);
    fs.writeFile(url, data, function (err) {
        if (err) {
            console.error(err);
        }
        rimraf(__dirname + '/tmp/*', function (err) {
            // console.log(err);
        });
    });
    let em = {
        id,
        name: req.body.name,
        age: req.body.age,
        sex: req.body.sex,
        phone: req.body.phone,
        idCard: req.body.idCard,
        role: req.body.role,
        // photo: file.originalname,
        photo: imgName,
    }
    //    console.log(em);
    empls.push(em);
    res.send('success');
});

//删除员工
app.post('/delEmpl.do', (req, res) => {
    let id = req.body.id;
    for (let i = 0; i < empls.length; i++) {
        let value = empls[i];
        if (value.id == id) {
            let url = __dirname + '/src/assets/img/' + value.photo;
            try {
                fs.unlinkSync(url);
            } catch (error) {
                fs.appendFile(__dirname + '/log/error.txt', error.message, (err) => {
                    if (err) throw err;
                });
                res.send('fail')
                return;
            }
            empls.splice(i, 1);
            res.send('success');
            return;
        }
    }
    res.send('fail');
});
// app.post('/delEmpl.do', (req, res) => {
//     let id = req.body.id;
//     for (empl of empls) {
//         if (id == empl.id) {
//             empl.state = 0;
//             // empls.splice(id-1,1);
//             res.send('success');
//             return;
//         }
//     } res.send('fail');
// });

//修改员工信息
app.get('/queryEmplsById', (req, res) => {
    let id = req.query.id;
    let newArr = empls.filter(value => {
        return value.id == id;
    });
    console.log(newArr);
    res.send(newArr[0]);
});


server.listen(9901);
console.log('Hotel Manage Startup Success in 9901');
